package com.zp.manager.disruptor;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.zp.domain.entity.User;
import com.zp.manager.websocket.PictureEditRequestMessage;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;

/**
 * 生产者(发送消息)
 */
@Component
public class PictureEditEventProducer {

    @Resource
    Disruptor<PictureEditEvent> pictureEditEventDisruptor;

    /**
     * 发送消息
     *
     * @param message   传递的消息
     * @param session   当前用户会话
     * @param user      当前用户
     * @param pictureId 图片id
     */
    public void publishEvent(PictureEditRequestMessage message, WebSocketSession session, User user, Long pictureId) {
        // 获取环形数组
        RingBuffer<PictureEditEvent> ringBuffer = pictureEditEventDisruptor.getRingBuffer();
        // 获取放置事件的位置
        long next = ringBuffer.next();
        PictureEditEvent event = ringBuffer.get(next);
        event.setPictureEditRequestMessage(message);
        event.setSession(session);
        event.setUser(user);
        event.setPictureId(pictureId);
        // 发布事件(发送消息)
        ringBuffer.publish(next);
    }

    /**
     * 优雅停机
     */
    @PreDestroy
    public void close() {
        pictureEditEventDisruptor.shutdown();
    }
}
